<script setup lang="ts">
import { ref, provide, onBeforeMount } from 'vue';
import {
  isShowKey, switchShow, switchLoginModelShowKey, getUserInfoKey,
  addMusicToListKey, addMusicToList, popMessageKey, messageQueueKey,
  Message, MessageType, setSrcAndPlayKey, playKey, playerKey, playIndexKey, nextMusicKey,
  lastMusicKey, playingMusicDurationKey, updatePlayerSrcAndPlayKey, deleteSingerMusicKey,
  musicHistory, playListKey, deleteAllMusicKey, getPlayingMusicKey, collectAllKey
} from '@/type'
import MessagePop from './components/MessagePop.vue';
import axios from './plugins/axiosInstance';
import CommonHeader from './components/Common/CommonHeader.vue'
import MainContent from './components/MainContent.vue'
import { useStore } from '../src/stores/index.ts'
import Player from './components/player.vue';
import { addPlayTimes, getMyMusicList } from '@api';
import { storeToRefs } from 'pinia';
const store = useStore();
const BaseUrl = store.getBaseUrl();

/**
 * 记录当前音乐播放记录的时长
 * 用来统计播放量
 */
let playStartTime = ref(0)
let playDurationTime = ref(0)
/**
 * 是否展示登录侧边
 */
const isShow = ref(false);
/**
 * 消息队列
 */
const messageQueue = ref<Message[]>([]);
/**
 * 当前播放（playList）索引 
 */
const playIndex = ref(-1);
/**
 * 当前播放列表
 * 
 */
const playList = ref<musicHistory[]>([]);
// const playListHistory = ref([])
/**
 * 播放器对象
 */
const player = new Audio()
const playingMusicDuration = ref(0);
/**
 * 发送消息
 * @param message 消息
 * @param type 类型
 * @param callback 结束完动画后的回调
 */
const popMessage = (message: string, type: MessageType, callback?: Function) => {
  if (messageQueue.value.length === 0) {
    messageQueue.value.push({ message, type, callback });
  }
}
/**
 * 检查该歌曲是否已存在于歌单中，如果是则返回true 否则返回false
 * @param history musicHistory对象
 * @returns true / flase
 */
const checkMusicInList = (history: musicHistory) => {
  for (let i = 0; i < playList.value.length; i++) {
    console.log(playList.value[i].id == history.id);
    if (playList.value[i].name == history.name) {
      return true
    }
  }
  return false
}
/**
 * 设置添加一首歌到playList并播放
 * @param history 音乐历史记录对象
 */
const setSrcAndPlay = (history: musicHistory) => {
  if (addMusicToList(history)) {
    setPlayIndex(playList.value.length - 1);
    player.src = playList.value[playIndex.value].url as string;
    play()
  } else {
    if (playList.value.length == 0) {
      console.log("失败");

      return
    }
    player.src = playList.value[playIndex.value].url as string;
    play()
  }

}
/**
 * 仅添加一首歌到歌单
 * @param history 音乐历史记录对象 
 */
const addMusicToList = (history: musicHistory) => {
  console.log("添加的url", history.url);
  if (playList.value.length == 0) {
    history.url = BaseUrl + "/static/music/" + history.url
    playList.value.push(history);
    setPlayIndex(0)
    updatePlayerSrc()
    return true
  }
  if (!checkMusicInList(history)) {
    history.url = BaseUrl + "/static/music/" + history.url
    playList.value.push(history);
    return true
  }
  return false
}
/**
 * 改变当前播放的index
 * @param index 
 */
const setPlayIndex = (index: number) => {
  playIndex.value = index;
}
/**
 * 切到下一首歌
 * 当列表长度为1时不切换
 * 当列表长度大于1
 *  且当前为最后一首歌 index 设为 0 
 * 否则切到下一首歌
 */
const nextMusic = () => {
  if (playList.value.length === 0) {
    return;
  }
  if (playIndex.value === playList.value.length - 1) {
    if (playList.value.length !== 1) {
      setPlayIndex(0);
      updatePlayerSrc()
      play()
    }
  } else {
    if (playList.value.length !== 1) {
      setPlayIndex(playIndex.value + 1);
      updatePlayerSrc()
      play()
    }
  }
}
/**
 * 切到上一首歌
 */
const lastMusic = () => {
  if (playList.value.length === 0) {
    return;
  }
  if (playIndex.value !== 0) {
    if (playList.value.length != 1) {
      setPlayIndex(playIndex.value - 1)
      updatePlayerSrc()
      play()
    }
  } else if (playIndex.value === 0) {
    if (playList.value.length !== 1) {
      setPlayIndex(playList.value.length - 1)
      updatePlayerSrc()
      play()
    }
  }
}
/**
 * 删除单曲
 * @param index 待删除id 
 */
const deleteSingerMusic = (index: number) => {
  playList.value.splice(index, 1)
  if (playIndex.value == playList.value.length) {
    if (playList.value.length > 0) {
      setPlayIndex(playIndex.value - 1)
    } else {
      setPlayIndex(-1)
    }
  } else if (index == 0 && playIndex.value != 0) {
    if (playList.value.length > 0) {
      setPlayIndex(playIndex.value - 1)
    } else {
      setPlayIndex(-1)
    }
  } else if (index < playIndex.value) {

    setPlayIndex(playIndex.value - 1)
  } else if (index > playIndex.value) {
    console.log("xiaoyu");

    return
  }
  updatePlayerSrc()
}
/**
 * 删除播放列表中全部曲
 */
const deleteAllMusic = () => {
  playList.value.length = 0;
  playingMusicDuration.value = 0;
  setPlayIndex(-1)
  updatePlayerSrc()
}
const collectAll = () => {
  let ids = [] as string[]
  playList.value.forEach(item => {
    ids.push(item.id)
  })
  store.openCollectAllModel(ids);
}
/**
 * 当播放完毕时自动切歌
 */
player.addEventListener('ended', () => {
  sendPlay('ended')
  nextMusic()
})
const sendPlay = (type: 'ended' | 'pause') => {
  playDurationTime.value += Date.now() - playStartTime.value
  if (player.duration * 0.5 <= playDurationTime.value / 1000 && playStartTime.value != 0) {
    console.log("成功记录播放");
    let musicHistory = playList.value[playIndex.value]
    playDurationTime.value = 0
    addPlayTimes(musicHistory.id, musicHistory.typeId, musicHistory.from).then(res => {
      console.log(res.data);
    })
  }
  if (type == 'ended') {
    playDurationTime.value = 0
    playStartTime.value = 0
  }
  if (type == 'pause') {
    playStartTime.value = 0
  }
}
player.onpause = () => {
  sendPlay('pause')
}
player.onplay = () => {
  playStartTime.value = Date.now()
}
player.oncanplay = () => {
  playingMusicDuration.value = player.duration;
}
const play = () => {
  player.play();
  playStartTime.value = Date.now()
  playDurationTime.value = 0;
}
/**
 * 通过index更新播放src，无需传递参数
 */
const updatePlayerSrc = () => {
  if (playList.value.length === 0) {
    player.src = "";
    return
  }
  if (player.src !== playList.value[playIndex.value].url) {
    player.src = playList.value[playIndex.value].url;
  }
}
/**
 * 用于点击并播放 网页下方播放列表里的歌 
 */
const updatePlayerSrcAndPlay = (musicId: string) => {
  for (let i = 0; i < playList.value.length; i++) {
    if (playList.value[i].id === musicId) {
      setPlayIndex(i);
      updatePlayerSrc();
      play();
    }
  }
}
const switchShow: switchShow = () => {
  isShow.value = !isShow.value;
}
const user = storeToRefs(store).UserInfo
const getUserSlideInfo = () => {
  axios.get(BaseUrl + "/user/info", {
    params: {
      account: user.value.account
    }
  }).then(res => {
    if (res.data.code === 1) {
      store.isLogin = 1
      store.setUserInfo(res.data.data);
      getUserSocialInfo()
    } else {
      store.isLogin = -1
    }
  })
}
const getUserSocialInfo = () => {
  axios.get("user/socialInfo", {
    params: {
      id: user.value.id
    }
  }).then(res => {
    if (res.data.code === 1) {
      store.setSocialInfo(res.data.data)
      store.Login()
    }
  })
}
/*
  * 尝试获取一次用户信息，如果用户存在session时
*/
onBeforeMount(() => {
  getUserSlideInfo();
  getMyMusicList()
})
const getPlayingMusic = () => {
  return playList.value[playIndex.value];
}
/**
 * 去更多歌单页面
 */

provide(switchLoginModelShowKey, switchShow)
provide(isShowKey, isShow)
provide(addMusicToListKey, addMusicToList)
provide(getUserInfoKey, getUserSlideInfo)
provide(setSrcAndPlayKey, setSrcAndPlay)
provide(popMessageKey, popMessage)
provide(messageQueueKey, messageQueue.value)
provide(playerKey, player)
provide(playKey, play)
provide(playListKey, playList)
provide(playIndexKey, playIndex)
provide(nextMusicKey, nextMusic)
provide(lastMusicKey, lastMusic)
provide(playingMusicDurationKey, playingMusicDuration)
provide(updatePlayerSrcAndPlayKey, updatePlayerSrcAndPlay)
provide(deleteSingerMusicKey, deleteSingerMusic)
provide(deleteAllMusicKey, deleteAllMusic)
provide(getPlayingMusicKey, getPlayingMusic);
provide(collectAllKey, collectAll)

</script>

<template>
  <MessagePop />
  <CommonHeader />
  <MainContent />
  <Player />
</template>

<style scoped></style>
